<template>
    <div>
        <van-pull-refresh v-model="tabRefreshing" @refresh="tableViewRefresh">

            <van-list v-model="tableViewLoading" :finished="tableViewFinished" :finished-text='requestFinishedMessage'
                :error-text="requestErrorMessage" @load='tableViewLoadMore' :immediate-check="false"
                style="margin-bottom: 50px;">

                <van-cell v-for="(item, index) in tableViewDataList" :key="index" @click="cellDidSelectMethod(item)">
                    <div>
                        <div class="titlefont"> {{'【' + item.businessId+ '】' + item.businessName }}</div>
                        <div class="infosfont"> 项目名称: {{ item.projectName }}</div>
                        <div class="infosfont" style="display:flex;justify-content:space-between">
                            <div> 项目编码: {{ item.projectId }} </div>

                            <van-button v-if="showCellButton(item) "
                                style=" display: inline-block; margin:0 9px 0 9px; padding:0 9px 0 9px"
                                @click="cellButtonClick(item.projectId)" size="small" type="primary" color="#60a9ec">
                                {{ cellButtonTitle }}
                            </van-button>
                        </div>
                    </div>
                </van-cell>

                <!-- 请求第一页数据时，出现错误或无数据 展示空白提示界面
                请求后续数据时，只做弹窗提示 -->
                <div v-show="showEmptyView" class="text-c">
                    <img width="100px" height="100px" :src="require('@/assets/images/pic_nodata.png')"
                        style="margin: 120px 50px 0" @click="tableViewRefresh()" />
                    <div class="color-b font14" style="margin: 20px 0 0 15px">
                        暂无数据
                    </div>
                </div>

                <div v-show="showErrorView" class="text-c">
                    <img width="100px" height="100px" :src="require('@/assets/images/pic_neterror.png')" alt="获取数据失败"
                        style="margin: 120px 50px 0" @click="tableViewRefresh()" />
                    <div class="color-b font14" style="margin: 20px 0 0 15px">
                        {{ requestErrorMessage }}
                    </div>
                </div>

            </van-list>
        </van-pull-refresh>
    </div>
</template>

<script>

import { requestDrawupSJListData, checkProjectStartStatus, findProjectStartModelByProjectID } from "@/api/dictapi";
import jDrawupUtil, { ChooseSJ_KEY, DrawupChooseType_SJ, dict_xmbg_code, dict_xmjd_code, dict_xmkg_code } from "../../assets/js/dict_process_helper";
import jTool from "@/assets/js/jHelper";

import { Toast, Dialog } from "vant";
import { Notify } from "vant";
import { mapGetters } from "vuex";
import moment from 'moment'

export default {
    name: 'sjlistview',
    data() {
        return {

            requestParam: {
                page: 1, rows: 10, size: 10,
                businessId: '', // 商机ID
                projectID: '',  // 项目ID
                startDate: '',  // 创建时间范围的 起始值
                endDate: '',    // 创建时间范围的 终止值
            },

            requestFinishedMessage: '',
            requestErrorMessage: '',

            tableViewDataList: [],
            tabRefreshing: false,
            tableViewLoading: false,
            tableViewFinished: false,

        
        }
    },

    props: ['pushParams'],

    computed: {
        ...mapGetters(["user"]),
        ...mapGetters(["userinfo"]),

        showEmptyView () {

            return this.requestParam.page === 1 && this.tableViewDataList.length === 0 && jTool.stringIsEmpty(this.requestErrorMessage);
        },

        showErrorView() {

            return this.requestParam.page === 1 && !jTool.stringIsEmpty(this.requestErrorMessage);
        },


        cellButtonTitle(){

            if (this.pushParams.processID === dict_xmjd_code) {
                return '【项目报送】';
            }
            else if (this.pushParams.processID === dict_xmkg_code) {
                return '【项目开工】'
            }

            return '';
        },
        
    },

    created() {

        // 重置  确保请求的是第一页数据，且删除缓存数据
        this.requestParam = {
            page: 1, rows: 10, size: 10,
            businessId: '', // 商机ID
            projectID: '',  // 项目ID
            startDate: '',  // 创建时间范围的 起始值
            endDate: '',    // 创建时间范围的 终止值
        };

        this.tableViewDataList = [];
        this.tableViewRefresh()
    },

    mounted() {

    },

    activated() {

        
    },

    methods: {

        // 查询
        requestDataWithFliterCondition(params) {

            Object.assign(this.requestParam, params);
            this.tableViewRefresh();
        },

        tableViewRefresh() {

            this.requestParam.page = 1;

            this.tabRefreshing = true;

            this.tableViewLoading = true;
            this.tableViewFinished = false;
            this.requestListDatas();
        },

        tableViewLoadMore() {

            if (!jTool.stringIsEmpty(this.requestFinishedMessage)) {

                console.log('dsdsdsdsdsd');
                this.tableViewLoading = false
                this.tableViewFinished = true;
            }
            else {

                this.tabRefreshing = false;
                this.requestListDatas();
            }
        },

        requestListDatas() {

            // ！！！！！！测试代码 记得删除
            // if (this.pushParams.processID === dict_xmjd_code) {
            //     this.requestParam.businessId = '371202105140018';
            // }

            let urlChip = jDrawupUtil.getSJListURLWithCode(this.pushParams.processID);
            requestDrawupSJListData(urlChip, this.requestParam)
                .then((result) => {

                    if (!result.data) {
                        this.tableViewFinished = true;
                        this.requestCompletion('result.message');
                        return;
                    }

                    let listdetails = [];
                    if (result.data.data.content) {
                        listdetails = listdetails.concat(result.data.data.content);
                    }

                    if (this.requestParam.page == 1) {
                        this.tableViewDataList = listdetails;
                    }
                    else
                    {
                        this.tableViewDataList = this.tableViewDataList.concat(listdetails);
                    }

                    if (result.data.data.totalPages <= this.requestParam.page) {
                        this.requestFinishedMessage = '没有更多数据！';
                        this.tableViewFinished = true;
                    }
                    else
                    {
                        this.requestParam.page++;
                        this.requestFinishedMessage = '';
                    }

                    this.requestCompletion('');
                })
                .catch((error) => {
                    this.tableViewFinished = true;
                    this.requestCompletion('获取数据失败,请稍后重试');
                });
        },


        requestCompletion(error) {

            this.tabRefreshing = false;
            this.tableViewLoading = false

            if (!jTool.stringIsEmpty(error)) {
                this.requestErrorMessage = error;
                Notify({ type: 'warning', message: error })
            }
        },

        timeUtil(value) {
            return moment(value).format('YYYY-MM-DD HH:mm:ss');
        },

        // 
        showCellButton(item) {

            ///  项目进度 进度报送 按钮
            if (this.pushParams.processID === dict_xmjd_code) {
                return !jTool.stringIsEmpty(item.createdTime);
            }
            ///  项目开工 发起开工 按钮
            else if (this.pushParams.processID === dict_xmkg_code) {
                return item.currentState === '未发起'
            }

            return false;
        },

        cellButtonClick(projectId) {

            if (this.pushParams.processID === dict_xmjd_code) {
                this.xmjdButtonClick(projectId);
            }
            else if (this.pushParams.processID === dict_xmkg_code) {
                this.xmkgButtonClick(projectId);
            }
        },

        /// 项目进度 - 项目进度列表 - 详情起草
        xmjdButtonClick(projectId) {

            // 网络请求校验是否可以 进度报送
            // 完成项目开工流程  才可以进度报送
            Toast.loading({ message: "加载中", forbidClick: false });
            findProjectStartModelByProjectID(projectId)
                .then((result) => {

                    Toast.clear();
                    let responseData = result.data.data;
                    if (responseData != null && responseData != undefined) {

                        // 目进度列表
                        let pushParams = this.pushParams;
                        pushParams.projectId = projectId;
                        this.$router.push(
                            {
                                name: 'drawup_xmjd_tab',
                                query: pushParams
                            }
                        )
                    }
                    else {
                        let message = '请先在售中管理-项目实施菜单下完成项目开工流程，未开工项目不可进行进度报送！';
                        Dialog.alert({ title: '温馨提示', message: message });
                    }
                })
                .catch((error) => {
                    Toast.clear();
                    Notify({ type: 'warning', message: '进度报送请求失败,请稍后重试' })
                });
        },


        /// 项目开工 - 发起开工 详情起草
        xmkgButtonClick(projectId) {

            /// 网络请求校验是否可以 发起开工起草
            /// flag: 1 请完成项目交接  2 请完成项目里程碑  3 可以起草  
            Toast.loading({ message: "加载中", forbidClick: false });
            checkProjectStartStatus(projectId)
            .then((result) => {

                Toast.clear();
                let flag = result.data.data.flag;
                if (flag == 3) {

                    // 开工起草
                    let pushParams = this.pushParams;
                    pushParams.projectId = projectId;
                    this.$router.push(
                        {
                            name: 'xmkg',
                            query: pushParams
                        }
                    )
                }
                else
                {
                    let message = (flag === 1 ? '请完成项目交接' : (flag === 2 ? '请完成项目里程碑' : "暂时无法起草"));
                    Dialog.alert({ title: '温馨提示', message: message });
                }
            })
            .catch((error) => {
                Toast.clear();
                Notify({ type: 'warning', message: '起草请求失败,请稍后重试' })
            });
        },


        cellDidSelectMethod(value) {

            if (this.pushParams.transType === DrawupChooseType_SJ) {
                
                if (jTool.stringIsEmpty(value.businessId)) {
                    Toast({ type: 'text', message: '请选择带有【商机编码】的项目！', duration: 1000 });
                    return;
                }

                /// 选中的商机数据，缓存本地 - 回到项目变更 详情，选中的商机带回去
                if (this.pushParams.processID === dict_xmbg_code) {
                    localStorage.setItem(ChooseSJ_KEY, JSON.stringify(value));
                    this.$router.back(-1);
                }
            }

            // this.$router.push(
            //     {
            //         name: 'srqrdetail',
            //         query: {
            //             processInstId: value.receiptCode,
            //             processDefName: value.processDefName,
            //             location: value.activityDefId,
            //             pmInsId: value.receiptCode,
            //             todoType: todoType,
            //             workItemId: value.wfId,
            //             pmInsType: value.pmInsType,
            //             wfnid: value.wfnid, //待阅使用
            //             isdraw: '0'
            //         }
            //     }
            // )
        }
    }
}
</script>

<style scoped>

</style>